<?php
/**
 * @describe 控制器基类
 *
 * @author wlx
 * @since 2018/11/6
 */

namespace App\Http\Controllers;


use App\Services\GeneralTool;
use Dingo\Api\Routing\Helpers;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Log;

class BaseController extends Controller
{
    use Helpers;

    /**
     * 默认返回成功
     * @var int
     */
    protected $statusCode = 200;


    /**
     * 设置状态码
     *
     * @param int $statusCode
     */
    protected function setStatusCode($statusCode)
    {
        $this->statusCode = $statusCode;

    }


    /**
     * 统一数据返回方法
     *
     * @param array $data
     * @param string $message
     *
     * @return array
     */
    protected function createResult(array $data = [], $message = '')
    {
        return response()->json([
            'code'    => $this->statusCode,
            'message' => $this->getResultMessage($message),
            'data'    => $data
        ]);
    }

    /**
     * 统一参数验证失败返回方法
     * @param array $details
     * @param string $message
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function createValidateResult(array $details = [], $message = '')
    {
        return response()->json([
            'code'    => $this->statusCode,
            'message' => $this->getResultMessage($message),
            'details' => $details
        ]);
    }

    /**
     * 从字典中获取输出消息
     * @param string $message
     *
     * @return array|null|string
     */
    private function getResultMessage($message)
    {
        if (!$message) {
            $message = Lang::get('globalcodes.' . $this->statusCode);
        }
        return $message;
    }

    /**
     * 记录错误日志
     *
     * @param \Exception $e
     * @param string $message
     */
    public function addErrorLog(\Exception $e, $message)
    {
        $arr = [
            '[message]' . $message,
            '[file]' . $e->getFile(),
            '[line]' . $e->getLine(),
            '[error]' . $e->getMessage()
        ];
        $message = implode(' ', $arr);
        $param = request()->all();
        $param['ip'] = GeneralTool::getRealIpAddr();
        Log::error($message, $param);
    }


}